import React from 'react'
import { useDispatch , useSelector} from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { Layout, Menu } from 'antd'
import * as Icons from '@ant-design/icons'
import MenuConfig from '../../config'
import { treeEach } from '../../utils'
import { selectMenuList } from '../../store/reducers/tab'
const { Sider } = Layout

// 动态获取icon
const iconToElement = name => React.createElement(Icons[name])
// 处理菜单的数据
const items = MenuConfig.map(item =>{
    // 没有子菜单
    const menu = {
        key: item.path,
        icon: iconToElement(item.icon),
        label: item.label
    }
    // 有子菜单
    if(item.children) {
        menu.children = item.children.map(subItem => {
            return {
                key: subItem.path,
                icon: iconToElement(subItem.icon),
                label: subItem.label
            }
        })
    }
    return menu
})

const CommonAside = ({ isCollapsed }) => {
    const navigate = useNavigate()
    const dispatch = useDispatch()
    // 添加数据到store
    const setTabsList = val =>{
       dispatch(selectMenuList(val))
    }
    const selectMenuKey =   useSelector(state =>state.tab.selectMenuKey)
    const selectMenu =  menu => {
        let currentMenu
        const { key } = menu
        treeEach(MenuConfig,'children','name',item =>{
            if(item.path === key) {
                currentMenu = item
            }
        })
        setTabsList({
            path: currentMenu.path,
            name: currentMenu.name,
            label: currentMenu.label
        })
        navigate(key)
    }
    return (
        <Sider trigger={null} collapsible collapsed={isCollapsed}>
            <h3 className="app-name">测试</h3>
            <Menu
                theme="dark"
                mode="inline"
                defaultSelectedKeys={['1']}
                selectedKeys={[selectMenuKey]}
                items={items}
                style={ { height: '100%'} }
                onClick={selectMenu}
            />
        </Sider>
    )
}

export default CommonAside
